<?php
/**
* Author: Porlock
* Link: www.porlockz.com
* Date: 2018-03-30 16:40:48
* Last Modified time: 2018-04-16 20:06:59
*/
/**
 * 展示现有题目情况
 * 1.读取数据库
 * 2.
 */
session_start();
require_once ('../init.php');
require_once ('includes/lib/func_rightCtrl.php');
require_once ('includes/lib/func_admin.php');
// 权限控制
admin_rightCtrl();
if($_SESSION['level'] == 0){
	require_once ('includes/views/root_header.php');
}
elseif ($_SESSION['level'] == 1) {
	require_once ('includes/views/admin_header.php');
}
if (@$_GET['action'] == ''){

	$query   = "SELECT `tid`,`point`,`title`,`description`,`link`,`type`,`solved` FROM `tasks`";
    $sth     = $dbh->prepare($query);
    $sth -> execute();
    $rownum = $sth->rowCount();
    //表格头
    echo <<<EOT
    <link href="/afctf/css/announce.css" rel="stylesheet" type="text/css" media="all"/>
    <script type="text/javascript" src="../layui/layui.all.js"></script>
	<div class="challenge_table">
		<blockquote class="layui-elem-quote">赛题管理</blockquote>
		<table lay-filter="chtable" lay-data="{ id:'idTest'}">  
		<thead>  
		<tr>  
		  <th lay-data="{field:'tid'}">题目id</th>  
		  <th lay-data="{field:'point'}">题目分值</th>  
		  <th lay-data="{field:'title'}">题目标题</th>  
		  <th lay-data="{field:'description'}">题目概述</th>
		  <th lay-data="{field:'link'}">题目链接</th> 
		  <th lay-data="{field:'type'}">题目分类</th>
		  <th lay-data="{field:'solved'}">已解答人数</th>  
		  <th lay-data="{fixed: 'right', align:'center', toolbar: '#barDemo'}">操作</th>  
		</tr>  
		</thead>  
		<tbody>
EOT;
	//表格内容
    for($i = 0;$i < $rownum; $i++){
    	$result  = $sth -> fetch();
    	$tid = $result['tid'];
    	$point = $result['point'];
    	$title = $result['title'];
    	$description = $result['description'];
    	$link = $result['link'];
    	$type = $result['type'];
    	$solved = $result['solved'];
    	echo <<<EOT
		  <tr>
		    <td>$tid</td>
		    <td>$point</td>
		    <td>$title</td>
		    <td>$description</td>
		    <td>$link</td>
		    <td>$type</td>
		    <td>$solved</td>
		    <td></td>
		  </tr>
EOT;
    }

    //表格尾
	echo <<<EOT
			</tbody>
		</table>
	</div>
		<div style="text-align:center">
			<a href="?action=challenge">
				<button class="layui-btn layui-btn-lg layui-btn-normal">发布题目</button>
			</a>
		</div>
		<script type="text/javascript">
			$("#a_home").removeClass("active");
			$("#a_challenge").addClass("active");
		</script>
		<script type="text/html" id="barDemo"> 
			<a class="layui-btn layui-btn-xs" lay-event="edit">编辑</a>  
			<a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="del">删除</a>  
		</script>  
		<script type="text/javascript">
			layui.use(['jquery','layer','table'], function(){  
				var layer = layui.layer  
				,element = layui.element  
				,$= layui.$  
				,table=layui.table;  

				//转换静态表格  
				table.init('chtable', {limit: 50});  
	 
				//监听工具条  
				table.on('tool(chtable)', function(obj){  
					var data = obj.data;
					var title_id = data['tid'];
					editurl = 'edit.php?tid=';
					editurl = editurl + title_id;
					delurl = 'del.php?tid=';
					delurl = delurl + title_id;
					if(obj.event === 'edit'){
						layer.open({
							type: 2,
				            title: "编辑题目",
				            content: editurl,
				            area: [window.innerWidth * 1.5 / 3 + "px", window.innerHeight * 26 / 30 + "px"],
						});
					} 
					else if(obj.event === 'del'){  
						layer.confirm('确定删除这道题？', function(index){  
							obj.del();
							$.get(delurl,function(data){
						        if(data === '0'){
						        	layer.msg('题目删除失败', {
							          icon: 5,
							          time: 500 //2秒关闭（如果不配置，默认是3秒）
							        },);   
						        }
						        else if (data === '1'){
									layer.msg('题目删除成功', {
							          icon: 6,
							          time: 500 //2秒关闭（如果不配置，默认是3秒）
							        },);   
						        }
						    });
							layer.close(index);
						});  
					}  
				});  
			});	
		</script>

EOT;
}
/**
 * 出题
 */
elseif(@$_GET['action'] == 'challenge'){
	echo <<<EOT
	<div class="container">
	<link href="/afctf/css/announce.css" rel="stylesheet" type="text/css" media="all"/>
		<form class="layui-form main" method='POST' action='/afctf/admin/challenge.php?action=deal'>
			<blockquote class="layui-elem-quote">发布题目</blockquote>
			<div class="layui-form-item">
				<label class="layui-form-label">题目名</label>
				<div class="layui-input-block">
					<input name="ch_title" type="text" required  lay-verify="required" placeholder="请输入题目名" autocomplete="off" class="layui-input">
				</div>
			</div>
			<div class="layui-form-item layui-form-text">
				<label class="layui-form-label">题目描述</label>
				<div class="layui-input-block">
					<textarea name="ch_description" placeholder="请输入题目描述" class="layui-textarea"></textarea>
				</div>
			</div>
			<div class="layui-form-item">
				<label class="layui-form-label">题目链接</label>
				<div class="layui-input-block">
					<input name="ch_link" type="text" required  lay-verify="required" placeholder="请输入题目链接" autocomplete="off" class="layui-input">
				</div>
			</div>
			<div class="layui-form-item">
				<label class="layui-form-label">题目类型</label>
				<div class="layui-input-block">
					<select name="ch_type" lay-verify="required">
						<option value="Web">Web</option>
						<option value="Reverse">Reverse</option>
						<option value="Misc">Misc</option>
						<option value="Crypto">Crypto</option>
					</select>
				</div>
			</div>
			<div class="layui-form-item">
				<label class="layui-form-label">flag</label>
				<div class="layui-input-block">
					<input name="ch_flag" type="text" required  lay-verify="required" placeholder="请输入flag" autocomplete="off" class="layui-input">
				</div>
			</div>
			<div style="text-align:center">
	            <input class="submit layui-btn" type="submit"  value="提交">
	        </div>
		</form>
	</div>
	<script type="text/javascript" src="../layui/layui.all.js"></script>
	<script type="text/javascript">
			$("#a_home").removeClass("active");
			$("#a_challenge").addClass("active");
	</script>
	<script type="text/javascript">
		layui.use('element', function(){
			var $ = layui.jquery
	  		,element = layui.element; //Tab的切换功能，切换事件监听等，需要依赖element模块
		});
	</script>
EOT;
}
/**
 * 将题目数据存放至数据库
 */
elseif (@$_GET['action'] == 'deal') {
	$challengeurl = '/afctf/admin/challenge.php';
	$title = $_POST['ch_title'];
	$description = $_POST['ch_description'];
	$link = $_POST['ch_link'];
	// 如果没有输入协议头，补全为http协议
	if (!stristr($link,'http://') && !stristr($link,'https://')){
		$link = 'http://'.$link;
	}
	$type = $_POST['ch_type'];
	// 带包围的flag值
	$flag = $_POST['ch_flag'];
	// 做输入转义
	$title = htmlentities($title,ENT_QUOTES);
	$description = htmlentities($description,ENT_QUOTES);
	$link = htmlentities($link,ENT_QUOTES);
	$type = htmlentities($type,ENT_QUOTES);
	// $flag = htmlentities($flag,ENT_QUOTES);
	
	$description = preg_replace("/\r\n/",'<br>',$description);
	$description = preg_replace("[\s]",'&nbsp;',$description);
	// 1.取出flag内容
	$flagSplit = preg_split('/\{/', $flag);
	// 2.保存flag的外围，并对flag内容做hash
	$flagHead = $flagSplit[0];
	$flagContent = substr($flagSplit[1],0,-1);
	$hashContent = hash('sha256',$flagContent);
	// 3.将外围与做了hash后的flag内容拼接
	$flag = $flagHead.'{'.$hashContent.'}';
	// 4.保存到数据库中
	$query = "INSERT INTO `tasks` (`title`,`description`,`link`,`type`,`flag`) VALUES (:title,:description,:link,:type,:flag)";
    $sth = $dbh->prepare($query);
    $sth -> bindParam(":title",$title);
    $sth -> bindParam(":description",$description);
    $sth -> bindParam(":link",$link);
    $sth -> bindParam(":type",$type);
    $sth -> bindParam(":flag",$flag);
    $sth -> execute();
    msg_display('题目发布成功','success',$challengeurl);
}
require_once ('includes/views/footer.php');
?>